package net.wanho.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import net.wanho.util.CurrentUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date::new, Date.class);
        this.strictInsertFill(metaObject, "updateTime", Date::new, Date.class);

        Integer userId = CurrentUtils.getId();
        if (userId != null) {
            this.strictInsertFill(metaObject, "createBy", () -> userId, Integer.class);
            this.strictInsertFill(metaObject, "updateBy", () -> userId, Integer.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date::new, Date.class);

        Integer userId = CurrentUtils.getId();
        if (userId != null) {
            this.strictUpdateFill(metaObject, "updateBy", () -> userId, Integer.class);
        }
    }
}